import {defineStore} from 'pinia'
import { getRoutes } from "@/utils/api/login";
import {useGlobalUserStore} from "@/store/userGlobalStore";
export const useGlobalMenuStore = defineStore('menuGlobal', {
    state: () => {
        return {
            menuList: [],
            authSlideMenuMap:null
        }
    },
    actions:{
        //获取该用户对应的菜单树
        async getMenuTree(){
            let rolePerm = useGlobalUserStore().currentRolePerm;
            let routes = await getRoutes(rolePerm);
            const slideMenu =  this.normalizeSlideMenu(routes.data);
            this.menuList = slideMenu.authSlideMenuList;
            this.authSlideMenuMap = slideMenu.authSlideMenuMap;
        },
        normalizeSlideMenu(routes){
          const authMap = new Map();
          // 当前用户所有的路由
          const authSlideMenuList = [
            {
              path:'/',
              name:'首页',
              meta:{
                icon:'HomeFilled'
              }
            },
            ...routes
          ]
          // map 把所有的二级路径都映射到一级路径，用于导航守卫的判断
          const authSlideMenuMap = this.normalizeSlideItem(authSlideMenuList,authMap);
          // console.log(111,authSlideMenuMap);
          return {
            authSlideMenuList,
            authSlideMenuMap
          };
        },
        normalizeSlideItem(routes,authMap){
          routes.forEach(item => {
            authMap.set(item.path, item);
            if(item.children){
              return this.normalizeSlideItem(item.children,authMap);
            }
          });
          return authMap;
        }
    },
    persist: {
        enabled: true,
        strategies: [
          {
            //key: 'my_user',
            storage: localStorage, //如果不写，默认是sessionStorage
            //path: ["permissions", "currentRolePerm"], //配置哪些数据是需要持久化存储的，如果不写，默认都需要
          },
        ],
      },
})